<template>
  <div style="height: 60px">
    <createHeader :isBorder="true" :isBack="true" @isback="FnBack">
      {{ isEdit ? "修改裸金属商品" : "创建裸金属商品" }}
    </createHeader>
  </div>
  <div style="height: calc(100% - 60px)">
    <el-form :model="formData" ref="formRef" label-width="130px" label-position="left">
      <createCardColumn title="商品选择" style="margin-top: 10px">
        <template #default>
          <el-form-item label="请选择商品" prop="eks_goods" :rules="{validator: eks_goods_validate, trigger: ['blur', 'change']}">
            <el-button type="primary" @click="FnSearchGoods('eks')" :disabled="isEdit">搜索EKS_BMS商品</el-button>
          </el-form-item>
          <el-form-item label="商品ID">{{ eks_goods.goods_id }}</el-form-item>
          <el-form-item label="商品名称">{{ eks_goods.goods_name }}</el-form-item>
        </template>
      </createCardColumn>
      <createCardColumn title="对应裸金属商品" style="margin-top: 10px">
        <template #default>
          <el-form-item label="请选择CR商品"  prop="cr_goods" :rules="{validator: cr_goods_validate, trigger: ['blur', 'change']}">
            <el-button type="primary" @click="FnSearchGoods('cr')">搜索CR商品</el-button>
          </el-form-item>
          <el-form-item label="商品ID">{{ bms_goods.goods_id }}</el-form-item>
          <el-form-item label="商品名称">{{ bms_goods.goods_name }}</el-form-item>
          <el-form-item label="GPU数量" prop="gpu" :rules="{validator: gpu_validate, trigger: ['blur', 'change']}">
            <el-input-number :min="0" :max="99" :step="1" step-strictly v-model="formData.gpu"></el-input-number>
          </el-form-item>
          <el-form-item label="GPU标签" prop="gpu_type" :rules="{validator: gpu_type_validate, trigger: ['blur', 'change']}">
            <el-select placeholder="请选择GPU标签" :disabled="!formData.gpu" v-model="formData.gpu_type">
              <el-option v-for="(value, key) in gpu_type_list" :key="key" :label="value" :value="key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注信息">
            <el-input type="textarea" v-model="formData.remark" class="w-280" :maxlength="128"></el-input>
          </el-form-item>
        </template>
      </createCardColumn>
    </el-form>
    <div class="footer">
      <el-button @click="FnBack">取消</el-button>
      <el-button type="primary" @click="confirm">{{ isEdit ? '修改' : '创建' }}</el-button>
    </div>
  </div>
  <!-- eks商品 -->
  <GoodsChosen v-model:goods="eks_goods" v-model:az_id="eks_az_id" v-model:modelValue="visibleEKS" type="EKS_BMS"></GoodsChosen>
  <!-- 裸金属商品 -->
  <GoodsChosen v-model:goods="bms_goods" v-model:az_id="bms_az_id" v-model:modelValue="visibleBMS" type="CR"></GoodsChosen>
  <!-- 信息确认 -->
   <confirmDialog :content="showForm" v-model:visible="showFormVisible" @isCreate="FnIsCreate"></confirmDialog>
</template>
<script setup>
import { ref, reactive, defineAsyncComponent, watch, onMounted } from 'vue';
import createHeader from '@/components/createHeader.vue'; 
import createCardColumn from '@/components/createCardColumn.vue';
import bmsGoodsService from '@/service/eks/bmsgood.js'
import { ElMessageBox, ElMessage } from 'element-plus'
import confirmDialog from '@/components/confirmDialog.vue'
import {useRouter, useRoute} from 'vue-router'
const GoodsChosen = defineAsyncComponent(() => import('./components/GoodsChosen.vue'));
const props = defineProps({
  isEdit:{
    type: Boolean,
    default: false
  }
})
const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const visibleEKS = ref(false)
const visibleBMS = ref(false)
const eks_goods = ref({
  goods_id: '',
  goods_name: '',
})
const eks_az_id = ref('')
watch(() => eks_goods.value, (nVal) => {
  if(nVal) {
    formRef.value.clearValidate(['eks_goods'])
  }
})
const bms_goods = ref({
  goods_id: '',
  goods_name: '',
})
const bms_az_id = ref('')
watch(() => bms_goods.value, (nVal) => {
  if(nVal) {
    formRef.value.clearValidate(['cr_goods'])
  }
})
const formData = reactive({
  gpu: 8,
  remark: '',
  gpu_type: '',
})
const FnSearchGoods = (type) => {
  if (type === 'eks') {
    visibleEKS.value = true
  } else {
    visibleBMS.value = true
  }
}
const gpu_type_list = ref({})
const getGpuTypeList = () => {
  bmsGoodsService.getGpuType().then(res => {
    if(res.code === 'Success') {
      gpu_type_list.value = res.data ?? {}
    }
  })
}
getGpuTypeList()
watch(() => formData.gpu, (nVal) => {
  if(nVal === 0) {
    formData.gpu_type = ''
  }
})
// 表单校验
const eks_goods_validate = (rule, value, callback) => {
  if(!eks_goods.value.goods_id || !eks_goods.value.goods_name) {
    callback(new Error('请选择商品'))
  } else {
    callback()
  }
}
const cr_goods_validate = (rule, value, callback) => {
  if(!bms_goods.value.goods_id || !bms_goods.value.goods_name) {
    callback(new Error('请选择CR商品'))
  } else {
    callback()
  }
}
const gpu_validate = (rule, value, callback) => {
  if(value === null || value === undefined) {
    callback(new Error('请输入GPU数量'))
  } else {
    if(value === 0) {
      formRef.value.clearValidate(['gpu_type'])
    }
    callback()
  }
}
const gpu_type_validate = (rule, value, callback) => {
  if(formData.gpu && !value) {
    callback(new Error('请选择GPU标签'))
  } else {
    callback()
  }
}
const confirm = () => {
  formRef.value.validate(valid => {
    if(valid) {
      if(formData.gpu === 0 && !formData.gpu_type) {
        ElMessageBox.confirm(
          `当前未选择GPU标签，该商品为CPU商品，是否确定${props.isEdit ? '修改' : '创建'}`,
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          showConfirmDialog()
        })
      } else {
        showConfirmDialog()
      }
    }
  })
}
const showForm = reactive({})
const showFormVisible = ref(false)
const showConfirmDialog = () => {
  showForm['EKS商品ID'] = eks_goods.value.goods_id
  showForm['EKS商品名称'] = eks_goods.value.goods_name
  showForm['裸金属商品ID'] = bms_goods.value.goods_id
  showForm['裸金属商品名称'] = bms_goods.value.goods_name
  showForm['GPU数量'] = formData.gpu
  showForm['GPU标签'] = gpu_type_list.value[formData.gpu_type]
  showForm['备注信息'] = formData.remark
  showFormVisible.value = true
}
const FnIsCreate = (val) => {
  showFormVisible.value = false
  if(val) {
    createGoods()
  }
}
const createGoods = () => {
  let data = {
    goods_id: eks_goods.value.goods_id,
    goods_name: eks_goods.value.goods_name,
    bms_goods_id: bms_goods.value.goods_id,
    bms_goods_name: bms_goods.value.goods_name,
    gpu: formData.gpu,
    gpu_type_id: formData.gpu_type,
    remark: formData.remark
  }
  if(props.isEdit) {
    bmsGoodsService.editGoods(data).then(res => {
      if(res.code === 'Success') {
        ElMessage.success('修改成功！')
        router.push({name: 'eks_2_bmsGoods_list'})
      }
    })
  } else {
    bmsGoodsService.addBmsGoods(data).then(res => {
      if(res.code === 'Success') {
        ElMessage.success('创建成功！')
        router.push({name: 'eks_2_bmsGoods_list'})
      }
    })
  }
  
}

const FnBack = () => { router.push({name: 'eks_2_bmsGoods_list'}) }
const showGoodsDetail = (id) => {
  bmsGoodsService.getBmsGoods({goods_id: id}).then(res => {
    if(res.code === 'Success') {
      let curGoods = res.data ? res.data[0] : {}
      if(JSON.stringify(curGoods) !== '{}') {
        const {goods_id, goods_name, bms_goods_id, bms_goods_name, gpu, gpu_type_id, remark} = curGoods
        eks_goods.value.goods_id = Number(goods_id)
        eks_goods.value.goods_name = goods_name
        bms_goods.value.goods_id = Number(bms_goods_id)
        bms_goods.value.goods_name = bms_goods_name
        formData.gpu = Number(gpu)
        formData.gpu_type = gpu_type_id
        formData.remark = remark
      }
    }
  })
}

onMounted(() => {
  // 编辑数据回显
  if(props.isEdit && route.params.id) {
    showGoodsDetail(route.params.id)
  }

})
</script>
<style scoped lang="scss">
.footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-bottom: 40px;
}
</style>